package hello;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.Transaction;

import persistence.HibernateUtil;
import auction.model.Category2OneToManyEntity;
import auction.model.CategoryItem2OneToManyEntity;
import auction.model.CategoryItemManyToManyComponent;
import auction.model.CategoryManyToManyComponent;
import auction.model.Item2OneToManyEntity;
import auction.model.ItemManyToManyComponent;

public class HelloWorldManyToManyComponent
{
	
	
	public static void main(String[] args)throws Exception
	{

		
		Session s=HibernateUtil.getSessionFactory().openSession();
		Transaction tx=s.beginTransaction();

		
		CategoryManyToManyComponent catA =new CategoryManyToManyComponent("cat a "+new Date());
		ItemManyToManyComponent iA=new ItemManyToManyComponent("item a "+new Date());
		
		CategoryItemManyToManyComponent link=new CategoryItemManyToManyComponent("wei",catA,iA);
		
		catA.getCategorizedItems().add(link);
		
		//s.save(catA);
		//s.save(iA);
		
		tx.commit();
		s.close();
		
		
		
		Session s1=HibernateUtil.getSessionFactory().openSession();
		Transaction tx1=s1.beginTransaction();
		
		
		CategoryManyToManyComponent loadCat=(CategoryManyToManyComponent)s1.load(CategoryManyToManyComponent.class, 3L);
		ItemManyToManyComponent loadI=(ItemManyToManyComponent)s1.load(ItemManyToManyComponent.class, 3L);

		//construct the link object
		CategoryItemManyToManyComponent newLink=new CategoryItemManyToManyComponent("wei wei",loadCat,loadI);
		//remove relation
		loadCat.getCategorizedItems().remove(newLink);//Graceful Code! wrote by me:)
		
		CategoryManyToManyComponent loadCat2=(CategoryManyToManyComponent)s1.load(CategoryManyToManyComponent.class, 1L);
		loadCat2.getCategorizedItems().add(newLink);
		
		
		tx1.commit();
		s1.close();
		
		
		
		//HibernateUtil.stat();
		HibernateUtil.shutdown();
	
	}
	
	public static void getParent(Class clazz)
	{
		Class parent=clazz.getSuperclass();
	  if(parent !=null)
	  {
			System.out.println("###"+parent.getName());
			getParent(parent);
		}
	}
	
	static void out(Object obj)
	{
		System.out.println(obj);
	}
}
